package com.xuecheng.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.base.execption.TeachplanError;
import com.xuecheng.base.execption.TeachplanException;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.mapper.TeachplanMapper;
import com.xuecheng.base.mapper.TeachplanMediaMapper;
import com.xuecheng.base.model.dto.BindTeachplanMediaDto;
import com.xuecheng.base.model.dto.SaveTeachplanDto;
import com.xuecheng.base.model.dto.TeachplanDto;
import com.xuecheng.base.model.po.Teachplan;
import com.xuecheng.base.model.po.TeachplanMedia;
import com.xuecheng.base.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class TeachplanServiceImpl implements TeachplanService {
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;
    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {
        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTreeNodes(courseId);
        return teachplanDtos;
    }

    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {
        Long teachplanId = teachplanDto.getId();
        if (teachplanId == null){
            //新增
            Teachplan teachplan  = new Teachplan();
            BeanUtils.copyProperties(teachplanDto,teachplan);
            //排序字段，找到他的统计节点个数在这个数字上加一，作为排序字段
            //select count(1) from teachplan where course_id=? and parentid=?
            Long parentid = teachplanDto.getParentid();
            Long courseId = teachplanDto.getCourseId();
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId,courseId);
            queryWrapper.eq(Teachplan::getParentid,parentid);
            // 使用max获取当前最大的orderby值
            queryWrapper.select(Teachplan::getOrderby);
            queryWrapper.orderByDesc(Teachplan::getOrderby);
            queryWrapper.last("LIMIT 1");

            Teachplan maxOrderTeachplan = teachplanMapper.selectOne(queryWrapper);

            int newOrderby = 1; // 默认值
            if (maxOrderTeachplan != null && maxOrderTeachplan.getOrderby() != null) {
                newOrderby = maxOrderTeachplan.getOrderby() + 1;
            }
            teachplan.setOrderby(newOrderby);
            teachplanMapper.insert(teachplan);
        }else {
            //修改
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            BeanUtils.copyProperties(teachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }
    }
    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));

        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    @Override

    public void deleteTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan == null) {
            throw new XueChengPlusException("未找到对应课程计划");
        }
        if (teachplan.getParentid() == 0) {
            // 根节点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, id);
            int count = teachplanMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new TeachplanException(TeachplanError.HAS_CHILDREN_ERROR);
            }

        }
        //删除小章节的课程媒体
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, id);
        int count = teachplanMediaMapper.selectCount(queryWrapper);
        if (count > 0) {

            teachplanMediaMapper.delete(queryWrapper);
        }
        teachplanMapper.deleteById(id);

    }

    @Override
    public void moveTeachplan(Long id, String direction) {
        Teachplan current = teachplanMapper.selectById(id);
        if (current == null) {
            throw new XueChengPlusException("未找到对应课程计划");
        }

        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid, current.getParentid())
                .eq(Teachplan::getCourseId, current.getCourseId());

        Teachplan target;
        if ("up".equals(direction)) {
            // 上移：找 orderby 更小的上一个节点
            queryWrapper.lt(Teachplan::getOrderby, current.getOrderby())
                    .orderByDesc(Teachplan::getOrderby)
                    .last("LIMIT 1");
            target = teachplanMapper.selectOne(queryWrapper);
            if (target == null) {
                throw new XueChengPlusException("已经是第一个节点，无法继续上移");
            }
        } else if ("down".equals(direction)) {
            // 下移：找 orderby 更大的下一个节点
            queryWrapper.gt(Teachplan::getOrderby, current.getOrderby())
                    .orderByAsc(Teachplan::getOrderby)
                    .last("LIMIT 1");
            target = teachplanMapper.selectOne(queryWrapper);
            if (target == null) {
                throw new XueChengPlusException("已经是最后一个节点，无法继续下移");
            }
        } else {
            throw new XueChengPlusException("移动方向参数错误");
        }

        // 交换 orderby 值
        Integer currentOrder = current.getOrderby();
        Integer targetOrder = target.getOrderby();

        current.setOrderby(targetOrder);
        target.setOrderby(currentOrder);

        // 更新数据库
        teachplanMapper.updateById(current);
        teachplanMapper.updateById(target);
    }
}
